﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using YouTube.Model;
using System.Collections.ObjectModel;
using Microsoft.SilverlightMediaFramework.Utilities.Extensions;
using Microsoft.Phone.Shell;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace YouTube.Views
{
    public partial class MainView : PhoneApplicationPage
    {
        List<string> CategoryList = new List<string>();
        public MainView()
        {
            InitializeComponent();
            if (_photoUri == null)
            {
                _photoUri = new Uri("/Images/panorama-6.jpg", UriKind.Relative);
               

            } 
            this.LayoutUpdated += new EventHandler(MainView_LayoutUpdated);
            this.Loaded += new RoutedEventHandler(MainView_Loaded);
            categoryList.SelectionChanged += new SelectionChangedEventHandler(categoryList_SelectionChanged);
            SearchListList.SelectionChanged += new SelectionChangedEventHandler(SearchListList_SelectionChanged);
            Listbox1.SelectionChanged += new SelectionChangedEventHandler(Listbox1_SelectionChanged);
        }
        bool isnavigated = false;

        void MainView_LayoutUpdated(object sender, EventArgs e)
        {
            if (!isnavigated)
            {
                isnavigated = true; CategoryList.Add("All");
                CategoryList.Add("Autos & Vehicles");
                CategoryList.Add("Comedy");
                CategoryList.Add("Education");
                CategoryList.Add("Entertainment");
                CategoryList.Add("Film & Animation");
                CategoryList.Add("Gaming");
                CategoryList.Add("Howto & Style");
                CategoryList.Add("News & Politics");
                CategoryList.Add("Nonprofits & Activism");
                CategoryList.Add("People & Blogs");
                CategoryList.Add("Pets & Animals");
                CategoryList.Add("Science & Technology");
                CategoryList.Add("Sports");
                CategoryList.Add("Travel & Events");
                Dispatcher.BeginInvoke(() =>
                {
                    
                    categoryList.ItemsSource = CategoryList;
                    YouTubeClient.Instance.RegisterDevice(SuccessCallback);
                });
            }
        }

        void Listbox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Listbox1.SelectedItem != null)
            {
                var videoid = Listbox1.SelectedItem as VideoModel;
                LoadVideo(videoid.VideoId);
                //NavigationService.Navigate(new Uri(string.Format("/Views/VideoPlay.xaml?VideoID={0}", videoid.VideoId), UriKind.Relative));
            }
            Listbox1.SelectedItem = null;
        }

        void SearchListList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (SearchListList.SelectedItem != null)
            {

                var videoid = SearchListList.SelectedItem as VideoModel;
                if (null != videoid)
                    LoadVideo(videoid.VideoId);
                //NavigationService.Navigate(new Uri(string.Format("/Views/VideoPlay.xaml?VideoID={0}", videoid.VideoId), UriKind.Relative));
            } SearchListList.SelectedItem = null;
        }

        void categoryList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (categoryList.SelectedItem != null)
            {
                string Category = categoryList.SelectedItem.ToString();
                if (Category.Equals("Film & Animation"))
                {
                    Category = "1";
                }
                if (Category.Equals("Autos & Vehicles"))
                {
                    Category = "2";
                }
                if (Category.Equals("News & Politics"))
                {
                    Category = "news";
                }
                if (Category.Equals("Science & Technology"))
                {
                    Category = "28";
                }
                if (Category.Equals("People & Blogs"))
                {
                    Category = "22";
                }
                if (Category.Equals("Nonprofits & Activism"))
                {
                    Category = "29";
                }
                if (Category.Equals("Travel & Events"))
                {
                    Category = "19";
                }
                if (Category.Equals("Howto & Style"))
                {
                    Category = "26";
                }
                if (Category.Equals("Pets & Animals"))
                {
                    Category = "26";
                }
               
                NavigationService.Navigate(new Uri(string.Format("/Views/CategoryVideoView.xaml?CategoryId={0}", Category), UriKind.RelativeOrAbsolute));
            } categoryList.SelectedItem = null;
        }
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (_photoUri.OriginalString.Equals("/Images/panorama-6.jpg"))
            {
                _photoUri = new Uri("/Images/panorama_alexei1.jpg", UriKind.Relative); 
                SetPanoramaBackground(_photoUri);
            }
            else
            {
                _photoUri = new Uri("/Images/panorama-6.jpg", UriKind.Relative);
                SetPanoramaBackground(_photoUri);
            }
            base.OnNavigatedFrom(e);
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            SetPanoramaBackground(_photoUri);
            base.OnNavigatedTo(e);
        }
        Uri _photoUri;
        void MainView_Loaded(object sender, RoutedEventArgs e)
        {
            
            
           
        }
        public void SuccessCallback()
        {

            Dispatcher.BeginInvoke(() =>
            {


                YouTubeClient.Instance.GetTopRatedVideos(TopRatedCallback);
            });
        }
        private void SetPanoramaBackground(Uri uri)
        {
            youtubePano.Background = new ImageBrush
            {
                ImageSource = new BitmapImage(uri),Stretch= Stretch.UniformToFill,Opacity=0.5,
            };
              
        }
        private void TopRatedCallback(ObservableCollection<VideoModel> result)
        {
            Dispatcher.BeginInvoke(() =>
            {
                Listbox1.ItemsSource = result;
            });
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (!SearchText.Text.IsNullOrWhiteSpace())
            {
                ShowProgress();
                YouTubeClient.Instance.getViDeos(HttpUtility.UrlEncode( SearchText.Text), SearchResultCallback);
            }
        }

        private void ShowProgress()
        {
            ProgressIndicator indicator = new ProgressIndicator();

            indicator.IsVisible = true;
            indicator.IsIndeterminate = true;
            indicator.Value = 0.5;
            indicator.Text = "Loading ";
            SystemTray.IsVisible = true;
            Color[] backgroundcolors = new Color[] { Colors.Red, Colors.Gray, Colors.Green };
            Color[] foregroundcolors = new Color[] { Colors.White, Colors.Black };
            Binding b;
            b = new Binding("SelectedItem");
            b.Source = foregroundcolors.ToList();
            b.Mode = BindingMode.TwoWay;
            this.SetBinding(Microsoft.Phone.Shell.SystemTray.ForegroundColorProperty, b);
            //SystemTray.BackgroundColor = backgroundcolors.ToList()[0];
            // this.SetBinding(Microsoft.Phone.Shell.SystemTray.ForegroundColorProperty, b);
            SystemTray.SetProgressIndicator(this, indicator);
        }
        private static void HideProgress()
        {
            SystemTray.IsVisible = false;
        }
        private void SearchResultCallback(ObservableCollection<VideoModel> result)
        {
            if (result != null)
            {
                SystemTray.IsVisible = false;
                Dispatcher.BeginInvoke(() =>
                {
                    SearchListList.ItemsSource = result;
                });
            }
        }
        public void LoadVideo(string id)
        {
            ShowProgress();
            //YouTubeUrl=    new Uri("http://www.youtube.com/watch?v=7Q7vLqemc0w&feature=feedrec_grec_index");
            //YouTubeUrl.OriginalString
            //        .Remove("&feature=youtube_gdata")
            //        .Remove("http://www.youtube.com/watch?v=");
            VideoModel model = null;
            try
            {
                //YouTubeClient.Instance.getViDeos("ShreyaGoshal");
                bool flag;
                model = YouTubeClient.Instance.GetVideoFromId(new VideoId(id), this.PlayVideo, out flag);
                //this.viewmodel.Model = model;
                if (flag)
                {
                    this.PlayVideo(model);
                }
            }
            catch (Exception e)
            {
                if (base.NavigationService.CanGoBack)
                {
                    base.NavigationService.GoBack();
                }
            }

        }
        private VideoViewModel viewmodel = new VideoViewModel();
        bool videoLoaded = false;
        private void PlayVideo(VideoModel result)
        {
           
            Dispatcher.BeginInvoke(() =>
            {
                HideProgress();
                videoLoaded = true;
                this.viewmodel.Model = result;
                if (result != null)
                {

                    Microsoft.Phone.Tasks.MediaPlayerLauncher pl = new Microsoft.Phone.Tasks.MediaPlayerLauncher();
                    //pl.Media = result.MediaContentUriFormat2;
                    //pl.Show();
                    if (result.MediaContentUriFormat3 != null)
                    {
                        pl.Media = result.MediaContentUriFormat3; pl.Show();
                        // MediaPlayer.Source = result.MediaContentUriFormat3;
                    }
                    else if (result.MediaContentUriFormat2 != null)
                    {
                        pl.Media = result.MediaContentUriFormat2; pl.Show();
                        //MediaPlayer.Source = result.MediaContentUriFormat2;
                    }

                    else if (result.MediaContentUriFormat9 != null)
                    {
                        pl.Media = result.MediaContentUriFormat9; pl.Show();
                        // MediaPlayer.Source = result.MediaContentUriFormat9;
                    }
                    else
                    {
                        MessageBox.Show("Cannot Play back the file");
                    }

                    // MediaPlayer.Play();
                }
            });
            //if (playVideoError != null)
            //{
            //    PersistentPlaybackState.Instance.CurrentVideo.LastKnownPlaybackState = PlaybackState.VideoFailedToPlay;
            //    this.ShowErrorMessage(ErrorString.ExceptionToYouTubeError(playVideoError));
            //}
            //else
            //{
            //    this.ProgressBar.Visibility = Visibility.Collapsed;
            //    this.ProgressBar.IsIndeterminate = false;
            //    VideoModel model = this.viewmodel.Model;
            //    if (((model != null) && (model.MediaContentUriFormat2 == null)) && ((model.MediaContentUriFormat3 == null) && (model.MediaContentUriFormat9 == null)))
            //    {
            //        PersistentPlaybackState.Instance.CurrentVideo.LastKnownPlaybackState = PlaybackState.VideoFailedToPlay;
            //        this.ShowErrorMessage(Strings.ErrorDialog_NoPvtAPIAvailable);
            //    }
            //    else
            //    {
            //        Uri uri = null;
            //        if ((NetworkInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) || (NetworkInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet))
            //        {
            //            uri = model.MediaContentUriFormat3 ?? (model.MediaContentUriFormat9 ?? model.MediaContentUriFormat2);
            //        }
            //        else
            //        {
            //            uri = model.MediaContentUriFormat2 ?? (model.MediaContentUriFormat9 ?? model.MediaContentUriFormat3);
            //        }
            //        if (string.IsNullOrEmpty(this.vndQueryArgs))
            //        {
            //            this.MediaPlayer.Source = uri;
            //        }
            //        else if (uri.OriginalString.Contains("?"))
            //        {
            //            this.MediaPlayer.Source = new Uri(uri.OriginalString + "&" + this.vndQueryArgs);
            //        }
            //        else
            //        {
            //            this.MediaPlayer.Source = new Uri(uri.OriginalString + "?" + this.vndQueryArgs);
            //        }
            //        switch (PersistentPlaybackState.Instance.CurrentVideo.LastKnownPlaybackState)
            //        {
            //            case PlaybackState.NeverPlayed:
            //                if (PersistentPlaybackState.Instance.AppLaunchMode != LaunchMode.LaunchedNonHubWithVideo)
            //                {
            //                    this.StartInPausedState(0L);
            //                    break;
            //                }
            //                this.StartWithActivePlayback(0L);
            //                break;

            //            case PlaybackState.PausedByUser:
            //            case PlaybackState.TrickModeToEnd:
            //            case PlaybackState.RewoundToBeginning:
            //            case PlaybackState.VideoObscured:
            //            case PlaybackState.ScreenLocked:
            //            case PlaybackState.Tombstoned:
            //                this.StartInPausedState(PersistentPlaybackState.Instance.CurrentVideo.LastKnownPosition);
            //                break;

            //            case PlaybackState.PlayedToEnd:
            //                if (PersistentPlaybackState.Instance.AppLaunchMode != LaunchMode.LaunchedNonHubWithVideo)
            //                {
            //                    this.StartInPausedState(0L);
            //                    break;
            //                }
            //                this.StartWithActivePlayback(0L);
            //                break;

            //            case PlaybackState.VideoFailedToPlay:
            //                this.StartInPausedState(PersistentPlaybackState.Instance.CurrentVideo.LastKnownPosition);
            //                break;

            //            case PlaybackState.PlaybackActive:
            //                if (PersistentPlaybackState.Instance.AppLaunchMode != LaunchMode.LaunchedNonHubWithVideo)
            //                {
            //                    this.StartInPausedState(PersistentPlaybackState.Instance.CurrentVideo.LastKnownPosition);
            //                    break;
            //                }
            //                this.StartWithActivePlayback(0L);
            //                break;
            //        }
            //        this.SendToHub();
            //    }
            //}
        }

      
    }
}